package com.alex.zookeeper.crud;

import com.alex.zookeeper.BaseTest;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;

/**
 * 更新节点数据
 * 1. 同步
 * 2. 异步
 */
@Slf4j
public class ZKSet extends BaseTest {

    /**
     * 同步
     */
    @Test
    public void testSync() throws Exception {
        // arg0: 节点
        // arg1: 数据
        // arg2: 版本, -1代表不关心版本是否一致, 直接更新
        Stat stat = zooKeeper.setData("/setData", "setData".getBytes(), -1);
        if (stat != null) {
            log.info("after version: {}", stat.getAversion());
        }
    }

    /**
     * 异步
     */
    @Test
    public void testAsync() throws Exception {
        zooKeeper.setData("/setData", "setData1".getBytes(), -1, new AsyncCallback.StatCallback() {

            /**
             * 异步更新, 回调
             *
             * @param responseCode: 返回code, 0代表成功
             * @param path: 更新的节点路径
             * @param context: 上下文
             * @param stat: 节点状态
             */
            @Override
            public void processResult(int responseCode, String path, Object context, Stat stat) {
                log.info("resCode:{}, path:{}, context:{}", responseCode, path, context);
            }
        }, "-1");
    }
}
